package com.yumeko;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import uitl.RpcRequest;

import java.util.concurrent.Callable;

/**
 * @program: netty-dubbo-zhenghao
 * @description: 客户端 Handler
 * @author: Zheng Hao
 * @create: 2020-03-12 14:46
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    private ChannelHandlerContext context;//上下文
    private RpcRequest rpcRequest;

    //与服务器的连接创建后，就会被调用, 这个方法是第一个被调用并且只调用一次
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    //收到服务器的数据后，调用方法
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        rpcRequest = (RpcRequest) msg;
        notify();//唤醒等待的线程
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    //被代理对象调用, 发送数据给服务器，-> wait -> 等待被唤醒(channelRead) -> 返回结果 (3)-》5
    @Override
    public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(rpcRequest);
        wait();
        return rpcRequest.getResult();
    }


    //设置参数
    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }
}
